import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_patient.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/patient_manage/patient_add.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';

/// 患者列表
class PatientListPage extends StatefulWidget {
  static const String routeName = '/patient_list';

  const PatientListPage({Key key}) : super(key: key);

  @override
  _PatientListPageState createState() => _PatientListPageState();
}

class _PatientListPageState extends State<PatientListPage> {
  List<Patient> _items = [];

  // 是否有下一页
  int _nextPage = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('患者列表'),
        actions: [
          TextButton(
              onPressed: () {
                Navigator.push(context,
                        MaterialPageRoute(builder: (c) => PatientAddPage()))
                    .then((value) => _fetchData());
              },
              child: Text(
                '新增患者',
                style: TextStyle(color: Theme.of(context).primaryColor),
              ))
        ],
      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: _nextPage != 1,
        onRefresh: _fetchData,
        onLoading: _loadMore,
        child: ListView.separated(
          padding: EdgeInsets.symmetric(vertical: 10),
          itemBuilder: (c, i) => ItemPatient(
            item: _items[i],
            onDelete: () {
              DialogUtils.showAlertDialog(context, '提示', '确认删除？',
                  onPressed: () {
                Navigator.pop(context);
                _delete(i);
              });
            },
            onTap: () {
              Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (c) => PatientAddPage(id: _items[i].id)))
                  .then((value) {
                if (value != null && value) {
                  _fetchData();
                }
              });
            },
          ),
          separatorBuilder: (c, i) => CustomDivider(),
          itemCount: _items.length,
        ),
      ),
    );
  }

  void _fetchData() async {
    var params = {
      "attachDoctorId": SPUtils.getUser().id,
      "pageNo": 1, //页码
      "pageSize": Constants.limit, //每页条数
      "sort": "created_at", //排序字段
      "order": "desc" //排序方式
    };
    var data = await XHttp.postJson(Urls.PATIENT_LIST, params);
    _refreshController.refreshCompleted();
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Patient.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore() async {
    var params = {
      "attachDoctorId": SPUtils.getUser().id,
      "pageNo": _nextPage, //页码
      "pageSize": Constants.limit, //每页条数
      "sort": "created_at", //排序字段
      "order": "desc" //排序方式
    };
    var result = await XHttp.postJson(Urls.TIMELY_CONSULTATION_LIST, params);
    _refreshController.loadComplete();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Patient.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _delete(int index) async {
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.PATIENT_DELETE, {
      'id': _items[index].id,
    });
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _items.removeAt(index);
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
